package root.electronclass.electronclass.grade.rota

import android.content.res.ColorStateList
import android.os.Bundle
import android.view.View
import androidx.core.graphics.toColorInt
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import root.electronclass.electronclass.common.base.BasicAdapter
import root.electronclass.electronclass.common.base.BasicDialogFragment.Companion.CANCEL
import root.electronclass.electronclass.common.base.BasicDialogFragment.Companion.OK
import root.electronclass.electronclass.common.base.BasicDialogFragment.Companion.TITLE
import root.electronclass.electronclass.common.base.ViewBindingFragment
import root.electronclass.electronclass.common.util.ToastUtil
import root.electronclass.electronclass.databinding.FragmentClassManageRotaBinding
import root.electronclass.electronclass.databinding.FragmentClassManageRotaItemBinding
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.grade.model.ClassRota
import root.electronclass.electronclass.grade.repository.ClassRepository
import root.electronclass.electronclass.mvp.rest.ClassApi

/**
 *管理值日项
 * @author Lokiy
 * @date 2023/2/18 13:04
 */
class ClassManageRotaFragment : ViewBindingFragment<FragmentClassManageRotaBinding>() {

    private val adapter = BasicAdapter<ClassRota, FragmentClassManageRotaItemBinding> { bindingHolder, item ->
        bindingHolder.binding.itemAdd.isVisible = item.id == null
        bindingHolder.binding.itemColor.isVisible = item.id != null
        bindingHolder.binding.itemName.isVisible = item.id != null
        bindingHolder.binding.itemDelete.isVisible = item.id != null

        val color = item.color.orEmpty().ifEmpty { ClassRepository.rotasColors.random() }.toColorInt()
        val colorStateList = ColorStateList.valueOf(color)
        bindingHolder.binding.itemName.text = item.item
        bindingHolder.binding.itemName.setTextColor(color)
        bindingHolder.binding.itemColor.imageTintList = colorStateList
        bindingHolder.binding.itemDelete.setOnClickListener {
            removedList.add(item)
            refresh(list.toMutableList().also { it.remove(item) })
        }
        bindingHolder.binding.itemAdd.setOnClickListener {
            ClassAddRotaDialog().also {
                it.arguments = bundleOf(TITLE to "添加值日项", OK to "保存", CANCEL to "取消")
                it.onSuccess = { refresh() }
            }.show(childFragmentManager, "CARD")
        }
    }

    private val removedList = mutableListOf<ClassRota>()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.recycler.layoutManager = GridLayoutManager(requireContext(), 4)
        binding.recycler.adapter = adapter
        refresh()
        binding.save.setOnClickListener {
            if (removedList.isEmpty()) {
                requireActivity().finish()
                return@setOnClickListener
            }
            showProgress("操作中", "", true)
            lifecycleScope.launch(CoroutineExceptionHandler()) {
                val response = withContext(Dispatchers.IO) {
                    ClassApi.service.deleteClassRota(removedList.mapNotNull { it.id })
                }
                dismissProgress()
                if (response?.code == 200) {
                    ToastUtil.showToast(requireActivity(), response.msg ?: "操作成功")
                    activity?.finish()
                } else {
                    ToastUtil.showToast(requireActivity(), response?.msg ?: "操作失败，请重试")
                }
            }
        }
    }

    private fun refresh() {
        lifecycleScope.launch(CoroutineExceptionHandler()) {
            withContext(Dispatchers.IO) {
                ClassApi.service.getClassRotaList()?.rows ?: mutableListOf()
            }.let { list ->
                adapter.refresh(list.toMutableList().apply {
                    removeAll { removedList.contains(it) }
                    add(ClassRota(null, "添加值日项", ClassRepository.rotasColors.random()))
                })
            }
        }
    }
}